package me.android.library.common.service;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import java.lang.ref.WeakReference;

import lombok.extern.slf4j.Slf4j;
import mylab.base.foundation.event.AsyncEventSupporter;

@Slf4j
public class NotificationService implements AsyncEventSupporter {
    private static NotificationService instance;
    public static synchronized NotificationService getInstance(Context context) {
        if (instance == null) {
            instance = new NotificationService(context);
        }
        return instance;
    }

    public static final String DEFAULT_CHANNEL_ID = "default_channel";
    private static final String DEFAULT_CHANNEL_NAME = "默认通知";
    private static final String DEFAULT_CHANNEL_DESC = "应用常规通知";

    protected WeakReference<Context> contextRef;
    private final NotificationManagerCompat notificationManager;

    private NotificationService(Context context) {
        contextRef = new WeakReference<>(context.getApplicationContext());
        this.notificationManager = NotificationManagerCompat.from(context);
    }

    public void init() {
        log.info("service init:{}", getClass().getName());
        AsyncEventSupporter.super.registerEventListener();
        // 创建默认通知渠道
        createNotificationChannel(
                DEFAULT_CHANNEL_ID,
                DEFAULT_CHANNEL_NAME,
                DEFAULT_CHANNEL_DESC,
                NotificationManager.IMPORTANCE_DEFAULT
        );
    }

    public void dispose() {
        log.info("service dispose:{}", getClass().getName());
        AsyncEventSupporter.super.unregisterEventListener();
        contextRef.clear();
    }

    protected Context getContext() {
        return contextRef != null ? contextRef.get() : null;
    }


    /**
     * 创建通知渠道（Android 8.0+ 需要）
     */
    @SuppressLint("ObsoleteSdkInt")
    public void createNotificationChannel(
            @NonNull String channelId,
            @NonNull String channelName,
            @NonNull String description,
            int importance) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    channelId, channelName, importance
            );
            channel.setDescription(description);
            channel.enableLights(true);
            channel.setLightColor(Color.BLUE);
            channel.enableVibration(true);
            channel.setVibrationPattern(new long[]{100, 200, 300});

            notificationManager.createNotificationChannel(channel);
        }
    }

    /**
     * 发送基础文本通知
     */
    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendBasicNotification(
            int notificationId,
            @NonNull String title,
            @NonNull String content) {
        sendBasicNotification(notificationId, title, content, DEFAULT_CHANNEL_ID);
    }


    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendBasicNotification(
            int notificationId,
            @NonNull String title,
            @NonNull String content,
            @NonNull String channelId) {
        NotificationCompat.Builder builder = buildBaseNotification(
                channelId, title, content, null
        );

        notificationManager.notify(notificationId, builder.build());
    }

    /**
     * 发送带大图的通知
     */
    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendBigPictureNotification(
            int notificationId,
            @NonNull String title,
            @NonNull String content,
            @NonNull Bitmap bigPicture) {
        sendBigPictureNotification(notificationId, title, content, bigPicture, DEFAULT_CHANNEL_ID);
    }

    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendBigPictureNotification(
            int notificationId,
            @NonNull String title,
            @NonNull String content,
            @NonNull Bitmap bigPicture,
            @NonNull String channelId) {
        NotificationCompat.Builder builder = buildBaseNotification(
                channelId, title, content, null
        );

        builder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bigPicture));
        notificationManager.notify(notificationId, builder.build());
    }

    /**
     * 发送多行文本通知
     */
    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendBigTextNotification(
            int notificationId,
            @NonNull String title,
            @NonNull String content,
            @NonNull String bigText) {
        sendBigTextNotification(notificationId, title, content, bigText, DEFAULT_CHANNEL_ID);
    }

    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendBigTextNotification(
            int notificationId,
            @NonNull String title,
            @NonNull String content,
            @NonNull String bigText,
            @NonNull String channelId) {
        NotificationCompat.Builder builder = buildBaseNotification(
                channelId, title, content, null
        );

        builder.setStyle(new NotificationCompat.BigTextStyle()
                .bigText(bigText));

        notificationManager.notify(notificationId, builder.build());
    }

    /**
     * 发送进度条通知
     */
    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendProgressNotification(
            int notificationId,
            @NonNull String title,
            int progress,
            int maxProgress) {
        sendProgressNotification(notificationId, title, progress, maxProgress, DEFAULT_CHANNEL_ID);
    }

    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendProgressNotification(
            int notificationId,
            @NonNull String title,
            int progress,
            int maxProgress,
            @NonNull String channelId) {
        NotificationCompat.Builder builder = buildBaseNotification(
                channelId, title, "进度: " + progress + "%", null
        );

        builder.setProgress(maxProgress, progress, false)
                .setOngoing(true)
                .setOnlyAlertOnce(true);

        notificationManager.notify(notificationId, builder.build());

        // 进度完成后更新通知
        if (progress >= maxProgress) {
            builder.setContentText("已完成")
                    .setProgress(0, 0, false)
                    .setOngoing(false);

            notificationManager.notify(notificationId, builder.build());
        }
    }

    /**
     * 发送自定义 PendingIntent 的通知
     */
    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendNotificationWithIntent(
            int notificationId,
            @NonNull String title,
            @NonNull String content,
            @NonNull PendingIntent pendingIntent) {
        sendNotificationWithIntent(notificationId, title, content, pendingIntent, DEFAULT_CHANNEL_ID);
    }

    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    public void sendNotificationWithIntent(
            int notificationId,
            @NonNull String title,
            @NonNull String content,
            @NonNull PendingIntent pendingIntent,
            @NonNull String channelId) {
        NotificationCompat.Builder builder = buildBaseNotification(
                channelId, title, content, pendingIntent
        );

        notificationManager.notify(notificationId, builder.build());
    }

    /**
     * 取消通知
     */
    public void cancelNotification(int notificationId) {
        notificationManager.cancel(notificationId);
    }

    /**
     * 取消所有通知
     */
    public void cancelAllNotifications() {
        notificationManager.cancelAll();
    }

    /**
     * 检查通知权限
     */
    public boolean areNotificationsEnabled() {
        return notificationManager.areNotificationsEnabled();
    }

    /**
     * 构建基础通知 Builder
     */
    private NotificationCompat.Builder buildBaseNotification(
            @NonNull String channelId,
            @NonNull String title,
            @NonNull String content,
            PendingIntent pendingIntent) {

        if (pendingIntent == null) {
            // 创建默认的 PendingIntent（点击通知打开应用）
            Intent intent = getContext().getPackageManager().getLaunchIntentForPackage(
                    getContext().getPackageName()
            );
            pendingIntent = createPendingIntent(intent);
        }

        return new NotificationCompat.Builder(getContext(), channelId)
                .setSmallIcon(getDefaultSmallIcon())
                .setContentTitle(title)
                .setContentText(content)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setColor(ContextCompat.getColor(getContext(), android.R.color.holo_blue_dark));
    }

    /**
     * 创建兼容不同 Android 版本的 PendingIntent
     */
    @SuppressLint("ObsoleteSdkInt")
    private PendingIntent createPendingIntent(Intent intent) {
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            flags |= PendingIntent.FLAG_IMMUTABLE;
        }

        return PendingIntent.getActivity(getContext(), 0, intent, flags);
    }

    /**
     * 获取默认小图标资源
     */
    @DrawableRes
    private int getDefaultSmallIcon() {
        // 使用系统默认图标，实际项目中应替换为应用自身图标
        return android.R.drawable.ic_dialog_info;
    }
}